package com.wxxymakers.grademark.controller;

import com.wxxymakers.grademark.exception.ServiceException;
import com.wxxymakers.grademark.model.entity.WxItem;
import com.wxxymakers.grademark.model.entity.WxItemRecord;
import com.wxxymakers.grademark.model.entity.WxUser;
import com.wxxymakers.grademark.service.WxItemRecordService;
import com.wxxymakers.grademark.service.WxItemService;
import com.wxxymakers.grademark.utils.Const;
import com.wxxymakers.grademark.utils.ExcelUtils;
import jxl.write.WriteException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Instant;
import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2019/1/22 22:09
 * @DESCRIBE Excel表格统计控制器
 */
@RestController
@RequestMapping("/excel")
@RequiresRoles(value = {"admin", "college-admin"}, logical = Logical.OR)
@Slf4j
public class ExcelController {

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private WxItemService itemService;

    @Autowired
    private WxItemRecordService recordService;

    /**
     * 根据事件id导出记录excel
     * @param iid 事件id
     */
    @RequestMapping("/export/{iid}")
    public ResponseEntity<byte[]> exportByIID(@PathVariable Integer iid,
                                              @SessionAttribute(Const.CURRENT_USER) WxUser user) {
        String collegeName = "全校";
        Integer collegeId = null;
        if (user.getRole().getSign().equals("college-admin")) {
            collegeId = user.getCollageId();
            collegeName = user.getCollege().getName();
        }
        List<WxItem> items = itemService.list(null);
        List<WxItemRecord> records = recordService.list(iid, collegeId, true); // 只统计审核通过的记录

        ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
        try {
            excelUtils.exportWithIncident(items, records, collegeName, out);
            return ResponseEntity.status(200)
                    .contentLength(out.size())
                    .header(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment;filename=export_%s.xls", Instant.now().getEpochSecond()))
                    .body(out.toByteArray());
        } catch (IOException | WriteException e) {
            throw new ServiceException("导出失败！");
        }
    }
}
